#!/bin/bash

# DEM automated installation script
# Supports parameter configuration, default values as below, can be modified via external parameters

# Default configuration parameters
DEFAULT_DB_PORT_NUM=5239
DEFAULT_SYSDBA_PWD="Test_dameng123"
DEFAULT_SYSAUDITOR_PWD="Test_dameng123"
DEFAULT_TOMCAT_PORT=8080
DEFAULT_DEM_URL="http://127.0.0.1:8080/dem"
DEFAULT_INSTALL_SERVICE_KEY="999999"
DEFAULT_AGENT_SERVICEPORT=6363
DEFAULT_AGENT_APPPORT=6364

# Base path (directory of the script location)
BASE_PATH=$(cd "$(dirname "$0")"; pwd)
DEM_OUTPUT="$BASE_PATH/dem_output"
DMAGENT_HOME="$BASE_PATH/dmagent"
DB_HOME="$BASE_PATH/bin"
STATUS_FILE="$BASE_PATH/install_status.txt"

# Log file with timestamp (YYYYMMDD_HHMM format)
LOG_TIMESTAMP=$(date '+%Y%m%d_%H%M')
LOG_FILE="$BASE_PATH/install_log_${LOG_TIMESTAMP}.log"
# Use functions to display step information
log_info() {
    local message="[INFO] $(date '+%Y-%m-%d %H:%M:%S') - $1"
    echo "$message"
    echo "$message" >> "$LOG_FILE"
}

log_error() {
    local message="[ERROR] $(date '+%Y-%m-%d %H:%M:%S') - $1"
    echo "$message" >&2
    echo "$message" >> "$LOG_FILE"
}

# Initialize log file
init_log_file() {
    # Create log file and write header
    echo "=== DEM Installation Log - Started at $(date '+%Y-%m-%d %H:%M:%S') ===" > "$LOG_FILE"
    echo "Installation script: $(basename "$0")" >> "$LOG_FILE"
    echo "Base path: $BASE_PATH" >> "$LOG_FILE"
    echo "Log file: $LOG_FILE" >> "$LOG_FILE"
    echo "========================================================" >> "$LOG_FILE"
    echo "" >> "$LOG_FILE"
}

check_command_result() {
    if [ $? -ne 0 ]; then
        log_error "Command execution failed: $1"
        exit 1
    fi
}

# Check if a port is occupied - telnet primary, netstat/ss fallbacks
check_port_occupied() {
    local port=$1
    
    # Primary method: Use telnet to check if port is occupied
    if command -v telnet > /dev/null; then
        # Try to connect to the port, check if it's accessible
        if timeout 1 telnet 127.0.0.1 "$port" < /dev/null 2>&1 | grep -q "Connected"; then
            return 0  # Port is occupied
        fi
        return 1  # Port is available
    fi
    
    # Fallback method 1: Use ss if available
    if command -v ss > /dev/null; then
        # Check all listening ports for exact port match
        if ss -tuln state all | grep -q ":$port\b" 2>/dev/null; then
            return 0  # Port is occupied
        fi
        return 1  # Port is available
    fi
    
    # Fallback method 2: Use netstat if available
    if command -v netstat > /dev/null; then
        # Check all listening ports for exact port match
        if netstat -tuln | grep -q ":$port\b" 2>/dev/null; then
            return 0  # Port is occupied
        fi
        return 1  # Port is available
    fi
    
    # If no tools available, exit with error
    log_error "telnet, ss, and netstat commands not found, cannot check port occupancy"
    exit 1
}

# Check if step is already completed or should be skipped
is_step_completed() {
    local step_number=$1
    
    # Check if status file exists
    if [ -f "$STATUS_FILE" ]; then
        # Read the completed step number from status file
        local completed_step
        if completed_step=$(grep -oE '^STEP_([0-9]+)_COMPLETED$' "$STATUS_FILE" | sed 's/STEP_\([0-9]*\)_COMPLETED/\1/'); then
            # If current step is less than or equal to completed step, skip it
            if [ "$step_number" -le "$completed_step" ]; then
                return 0
            fi
        fi
    fi
    return 1
}

# Mark step as completed
mark_step_completed() {
    local step_number=$1
    
    # Overwrite status file with current step number
    echo "STEP_${step_number}_COMPLETED" > "$STATUS_FILE"
    log_info "Step $step_number marked as completed"
}

# Parse command line parameters
while [[ $# -gt 0 ]]; do
    case $1 in
        --port-num)
            PORT_NUM="$2"
            shift 2
            ;;
        --sysdba-pwd)
            SYSDBA_PWD="$2"
            shift 2
            ;;
        --sysauditor-pwd)
            SYSAUDITOR_PWD="$2"
            shift 2
            ;;
        --tomcat-port)
            TOMCAT_PORT="$2"
            shift 2
            ;;
        --dem-url)
            DEM_URL="$2"
            shift 2
            ;;
        --install-service-key)
            INSTALL_SERVICE_KEY="$2"
            shift 2
            ;;
        --help)
            echo "Usage: $0 [options]"
            echo "Options:"
            echo "  --port-num <port>             Database port (default: $DEFAULT_DB_PORT_NUM)"
            echo "  --sysdba-pwd <password>       SYSDBA password (default: $DEFAULT_SYSDBA_PWD)"
            echo "  --sysauditor-pwd <password>   SYSAUDITOR password (default: $DEFAULT_SYSAUDITOR_PWD)"
            echo "  --tomcat-port <port>          Tomcat port (default: $DEFAULT_TOMCAT_PORT)"
            echo "  --dem-url <URL>               DEM access URL (default: $DEFAULT_DEM_URL)"
            echo "  --install-service-key <key>  Installation service key (default: $DEFAULT_INSTALL_SERVICE_KEY)"
            echo "  --agent-serviceport <port>    Agent service port (default: $DEFAULT_AGENT_SERVICEPORT)"
            echo "  --agent-apport <port>         Agent app port (default: $DEFAULT_AGENT_APPPORT)"
            echo "  --help                        Show this help message"
            exit 0
            ;;
        *)
            log_error "Unknown parameter: $1"
            echo "Use --help to view help information"
            exit 1
            ;;
    esac
done

# Initialize log file first to ensure all logs are recorded
init_log_file

# Set parameter values, use passed values > defaults
PORT_NUM=${PORT_NUM:-$DEFAULT_DB_PORT_NUM}
SYSDBA_PWD=${SYSDBA_PWD:-$DEFAULT_SYSDBA_PWD}
SYSAUDITOR_PWD=${SYSAUDITOR_PWD:-$DEFAULT_SYSAUDITOR_PWD}
TOMCAT_PORT=${TOMCAT_PORT:-$DEFAULT_TOMCAT_PORT}
DEM_URL=${DEM_URL:-$DEFAULT_DEM_URL}
INSTALL_SERVICE_KEY=${INSTALL_SERVICE_KEY:-$DEFAULT_INSTALL_SERVICE_KEY}
AGENT_SERVICEPORT=${AGENT_SERVICEPORT:-$DEFAULT_AGENT_SERVICEPORT}
AGENT_APPPORT=${AGENT_APPPORT:-$DEFAULT_AGENT_APPPORT}

# Display configuration information
log_info "Starting DEM automated installation"
log_info "Configuration parameters:"
log_info "  Database port: $PORT_NUM"
log_info "  SYSDBA password: $SYSDBA_PWD"
log_info "  SYSAUDITOR password: $SYSAUDITOR_PWD"
log_info "  Tomcat port: $TOMCAT_PORT"
log_info "  DEM access URL: $DEM_URL"
log_info "  Install service key: $INSTALL_SERVICE_KEY"
log_info "  Agent service port: $AGENT_SERVICEPORT"
log_info "  Agent app port: $AGENT_APPPORT"
log_info "  Base path: $BASE_PATH"

# Step 0: Check port occupancy
log_info "Step 0: Check port occupancy"
if is_step_completed 0; then
    log_info "Step 0 already completed, skipping port checks"
else
    log_info "Checking port occupancy..."
    
    # Check database port
    if check_port_occupied "$PORT_NUM"; then
        log_error "Database port $PORT_NUM is already occupied"
        exit 1
    fi
    
    # Check DEM HTTP port
    if check_port_occupied "$TOMCAT_PORT"; then
        log_error "DEM HTTP port $TOMCAT_PORT is already occupied"
        exit 1
    fi
    
    # Check agent service port
    if check_port_occupied "$AGENT_SERVICEPORT"; then
        log_error "Agent service port $AGENT_SERVICEPORT is already occupied"
        exit 1
    fi
    
    # Check agent app port
    if check_port_occupied "$AGENT_APPPORT"; then
        log_error "Agent app port $AGENT_APPPORT is already occupied"
        exit 1
    fi
    
    log_info "All ports are available"
    mark_step_completed 0
fi

# Step 1: Initialize metadata database
log_info "Step 1: Initialize metadata database"
if is_step_completed 1; then
    log_info "Step 1 already completed, skipping"
else
    cd "$DB_HOME"
    ./dminit path="$BASE_PATH" db_name=demdb instance_name=demdb port_num="$PORT_NUM" SYSDBA_PWD="$SYSDBA_PWD" SYSAUDITOR_PWD="$SYSAUDITOR_PWD"
    check_command_result "Failed to initialize metadata database"
    mark_step_completed 1
fi

# Step 2: Register service
log_info "Step 2: Register service"
if is_step_completed 2; then
    log_info "Step 2 already completed, skipping"
else
    SERVICE_FILE="$DB_HOME/DmServicedem"
    SERVICE_TEMPLATE_DIR="$DB_HOME/service_template"

    if [ -f "$SERVICE_FILE" ]; then
        # Backup original file
        cp "$SERVICE_FILE" "$SERVICE_FILE.bak"
        
        # Modify DM_HOME and INI_PATH using actual configuration format
        # Use DB_HOME without /bin for DM_HOME path in case it config manually 
        DM_HOME_PATH="${DB_HOME%/bin}"
        
        # Update DM_HOME configuration - robust handling for different formats
        # First check if DM_HOME line exists
        if grep -q "DM_HOME=" "$SERVICE_FILE"; then
            # Replace any existing DM_HOME format (with or without quotes, different delimiters)
            sed -i "s|DM_HOME=.*|DM_HOME=\"$DM_HOME_PATH\"|" "$SERVICE_FILE"
        else
            # If DM_HOME line doesn't exist, add it (this should be rare)
            echo "DM_HOME=\"$DM_HOME_PATH\"" >> "$SERVICE_FILE"
        fi
        
        # Update INI_PATH configuration (without quotes)
        sed -i "s|%INI_PATH%[^[:space:]]*|INI_PATH=$BASE_PATH/demdb/dm.ini|" "$SERVICE_FILE"
        
        log_info "Service file updated: $SERVICE_FILE"
    else
        log_info "Service file does not exist, creating from template"
        
        # Check if service_template directory exists
        if [ -d "$SERVICE_TEMPLATE_DIR" ]; then
            # Look for exact template file "DmService" in service_template directory
            TEMPLATE_FILE="$SERVICE_TEMPLATE_DIR/DmService"
            
            if [ -f "$TEMPLATE_FILE" ]; then
                # Copy template to create DmServicedem
                cp "$TEMPLATE_FILE" "$SERVICE_FILE"
                
                # Modify DM_HOME and INI_PATH in the new service file using template placeholders
                # Use DB_HOME without /bin for DM_HOME path in case it config manually 
                DM_HOME_PATH="${DB_HOME%/bin}"
                sed -i "s|_REPLACE_SELF_DM_HOME|$DM_HOME_PATH|" "$SERVICE_FILE"
                sed -i "s|%INI_PATH%|\"$BASE_PATH/demdb/dm.ini\"|" "$SERVICE_FILE"
                
                log_info "Service file created from template: $SERVICE_FILE"
            else
                log_error "Template file does not exist: $TEMPLATE_FILE"
                exit 1
            fi
        else
            log_error "Service template directory does not exist: $SERVICE_TEMPLATE_DIR"
            exit 1
        fi
    fi
    mark_step_completed 2
fi

# Step 3: Start metadata database service
log_info "Step 3: Start metadata database service"
if is_step_completed 3; then
    log_info "Step 3 already completed, skipping"
else
    "$DB_HOME/DmServicedem" start
    if [ $? -eq 0 ]; then
        log_info "Metadata database service started successfully"
    else
        log_error "Failed to start metadata database service"
        exit 1
    fi
    
    # Wait for database service to fully start
    sleep 10
    mark_step_completed 3
fi

# Step 4: Extract DEM package
log_info "Step 4: Extract DEM package"
if is_step_completed 4; then
    log_info "Step 4 already completed, skipping"
else
    # Find DEM package using pattern matching
    DEM_ZIP=$(find "$BASE_PATH" -maxdepth 1 \( -name "dem_*.zip" -o -name "dem-*.zip" \) | head -n 1)
    if [ -n "$DEM_ZIP" ] && [ -f "$DEM_ZIP" ]; then
        unzip -o "$DEM_ZIP" -d "$BASE_PATH/"
        check_command_result "Failed to extract DEM package"
        log_info "DEM package extracted successfully"
    else
        log_error "No DEM package found in $BASE_PATH. Please ensure a dem_*.zip file exists."
        exit 1
    fi
    mark_step_completed 4
fi

# Step 5: Initialize metadata database table structure
log_info "Step 5: Initialize metadata database table structure"
if is_step_completed 5; then
    log_info "Step 5 already completed, skipping"
else
    DEM_INIT_SQL="$DEM_OUTPUT/dem_init.sql"
    if [ ! -f "$DEM_INIT_SQL" ]; then
        # If not found in DEM_OUTPUT, look in current directory
        if [ -f "$BASE_PATH/dem_init.sql" ]; then
            DEM_INIT_SQL="$BASE_PATH/dem_init.sql"
            log_info "Found dem_init.sql in base directory: $DEM_INIT_SQL"
        fi
    fi
    
    if [ -f "$DEM_INIT_SQL" ]; then
        # Use disql to execute SQL script
        "$DB_HOME/disql" "SYSDBA/$SYSDBA_PWD@localhost:$PORT_NUM" << EOF
start $DEM_INIT_SQL
quit
EOF
        check_command_result "Failed to initialize database table structure"
        log_info "Database table structure initialized successfully"
    else
        log_error "Initialization SQL file does not exist in either $DEM_OUTPUT or $BASE_PATH"
        exit 1
    fi
    mark_step_completed 5
fi

# Step 6: Extract tomcat package
log_info "Step 6: Extract tomcat package"
if is_step_completed 6; then
    log_info "Step 6 already completed, skipping"
    TOMCAT_HOME=$(find "$BASE_PATH" -maxdepth 1 -type d -name "apache-tomcat-*" | head -1)
else
    TOMCAT_ZIP=$(find "$BASE_PATH" -name "apache-tomcat-*.zip" | head -1)
    TOMCAT_HOME=$(find "$BASE_PATH" -maxdepth 1 -type d -name "apache-tomcat-*" | head -1)
    if [ -f "$TOMCAT_ZIP" ]; then
        if [ ! -d "$TOMCAT_HOME" ]; then
            log_info "Extracting tomcat package: $TOMCAT_ZIP"
            unzip -q "$TOMCAT_ZIP" -d "$BASE_PATH"
            check_command_result $? "Failed to extract tomcat package"
            log_info "Tomcat package extracted successfully"
            # Update TOMCAT_HOME after extraction
            TOMCAT_HOME=$(find "$BASE_PATH" -maxdepth 1 -type d -name "apache-tomcat-*" | head -1)
        else
            log_info "Tomcat directory already exists, skipping extraction"
        fi
    else
        log_error "Tomcat package does not exist: apache-tomcat-*.zip"
        exit 1
    fi
    mark_step_completed 6
fi

# Step 7: Modify tomcat's catalina.sh file
log_info "Step 7: Modify tomcat configuration"
if is_step_completed 7; then
    log_info "Step 7 already completed, skipping"
else
    CATALINA_FILE="$TOMCAT_HOME/bin/catalina.sh"
    if [ -f "$CATALINA_FILE" ]; then
        # Check if JAVA_OPTS with java.library.path already exists
        if ! grep -q "-Djava.library.path" "$CATALINA_FILE"; then
            # Add JAVA_OPTS setting at the beginning of the file
            sed -i "1i JAVA_OPTS=\"-server -Djava.library.path=$DB_HOME\"" "$CATALINA_FILE"
            log_info "Catalina.sh file updated with java.library.path"
        else
            log_info "Catalina.sh file already contains java.library.path setting, skipping modification"
        fi
    else
        log_error "Catalina.sh file does not exist: $CATALINA_FILE"
        exit 1
    fi
    mark_step_completed 7
fi

# Step 8: Modify tomcat's server.xml
log_info "Step 8: Modify server.xml configuration"
if is_step_completed 8; then
    log_info "Step 8 already completed, skipping"
else
    SERVER_XML="$TOMCAT_HOME/conf/server.xml"
    if [ -f "$SERVER_XML" ]; then
        # Extract IP address from DEM_URL (e.g., http://192.168.1.100:8080/dem -> 192.168.1.100)
        DEM_IP=$(echo "$DEM_URL" | sed -n 's|http://\([^:]*\):.*|\1|p')
        
        # Check if configuration already meets requirements
        # 1. Check if there's a Connector with target port, address, and HTTP protocol
        # 2. Check if maxPostSize is already set
        if grep -q "port=\"$TOMCAT_PORT\"" "$SERVER_XML" && grep -q "address=\"$DEM_IP\"" "$SERVER_XML" && grep -q "protocol=\"HTTP/1.1\"" "$SERVER_XML" && grep -q "maxPostSize=\"-1\"" "$SERVER_XML"; then
            log_info "Server.xml already has correct configuration, skipping modification"
        else
            # Backup original file only if modification is needed
            cp "$SERVER_XML" "$SERVER_XML.bak"
            
            # Modify Connector configuration with address attribute
            # Check if port="8080" protocol="HTTP/1.1" already exists
            if grep -q 'port="8080" protocol="HTTP/1.1"' "$SERVER_XML"; then
                # If exists, add maxPostSize, address, and modify port number
                sed -i "s|port=\"8080\" protocol=\"HTTP/1.1\"|port=\"$TOMCAT_PORT\" address=\"$DEM_IP\" protocol=\"HTTP/1.1\" maxPostSize=\"-1\"|g" "$SERVER_XML"
            else
                # If not exists, use the original replacement with address
                sed -i "s|<Connector port=\"8080\"|<Connector port=\"$TOMCAT_PORT\" address=\"$DEM_IP\" protocol=\"HTTP/1.1\" maxPostSize=\"-1\"|" "$SERVER_XML"
            fi
            
            log_info "Server.xml file updated, port set to: $TOMCAT_PORT, address set to: $DEM_IP"
        fi
    else
        log_error "Server.xml file does not exist: $SERVER_XML"
        exit 1
    fi
    mark_step_completed 8
fi



# Step 9: Deploy dem.war file
log_info "Step 9: Deploy dem.war file"
if is_step_completed 9; then
    log_info "Step 9 already completed, skipping"
else
    DEM_WAR="$DEM_OUTPUT/dem.war"
    if [ ! -f "$DEM_WAR" ]; then
        # If not found in DEM_OUTPUT, look in current directory
        if [ -f "$BASE_PATH/dem.war" ]; then
            DEM_WAR="$BASE_PATH/dem.war"
            log_info "Found dem.war in base directory: $DEM_WAR"
        fi
    fi
    
    TOMCAT_WEBAPPS="$TOMCAT_HOME/webapps"
    if [ -f "$DEM_WAR" ]; then
        cp "$DEM_WAR" "$TOMCAT_WEBAPPS/"
        check_command_result "Failed to copy dem.war file"
        log_info "dem.war file deployed to Tomcat"
    else
        log_error "dem.war file does not exist in either $DEM_OUTPUT or $BASE_PATH"
        exit 1
    fi
    mark_step_completed 9
fi

# Step 10: Start Tomcat service once and stop
log_info "Step 10: Start Tomcat service once and stop"
if is_step_completed 10; then
    log_info "Step 10 already completed, skipping"
else
    # Set execute permissions for catalina.sh, startup.sh and shutdown.sh
    if [ -f "$TOMCAT_HOME/bin/catalina.sh" ]; then
        chmod +x "$TOMCAT_HOME/bin/catalina.sh"
        log_info "catalina.sh execute permission set"
    else
        log_error "catalina.sh does not exist: $TOMCAT_HOME/bin/catalina.sh"
        exit 1
    fi

    if [ -f "$TOMCAT_HOME/bin/startup.sh" ]; then
        chmod +x "$TOMCAT_HOME/bin/startup.sh"
        log_info "startup.sh execute permission set"
    else
        log_error "startup.sh does not exist: $TOMCAT_HOME/bin/startup.sh"
        exit 1
    fi

    if [ -f "$TOMCAT_HOME/bin/shutdown.sh" ]; then
        chmod +x "$TOMCAT_HOME/bin/shutdown.sh"
        log_info "shutdown.sh execute permission set"
    else
        log_error "shutdown.sh does not exist: $TOMCAT_HOME/bin/shutdown.sh"
        exit 1
    fi

    "$TOMCAT_HOME/bin/startup.sh"
    check_command_result "Failed to start Tomcat"
    log_info "Tomcat started successfully"

    # Wait for Tomcat to start completely
    log_info "Sleep 60 seconds for waiting Tomcat to start completely..."
    sleep 60

    log_info "Stop Tomcat service"
    "$TOMCAT_HOME/bin/shutdown.sh"
    check_command_result "Failed to stop Tomcat"
    log_info "Tomcat shutdown command executed successfully"

    # Wait for Tomcat to stop completely and check if process is really terminated
    log_info "Waiting for Tomcat process to terminate..."
    sleep 10
    
    # Check if Tomcat process is still running
    TOMCAT_PROCESS=$(ps aux | grep -v grep | grep "$TOMCAT_HOME")
    if [ -n "$TOMCAT_PROCESS" ]; then
        log_warn "Tomcat process is still running, forcing termination..."
        # Force kill Tomcat process
        pkill -f "$TOMCAT_HOME"
        sleep 5
        
        # Check again
        TOMCAT_PROCESS=$(ps aux | grep -v grep | grep "$TOMCAT_HOME")
        if [ -n "$TOMCAT_PROCESS" ]; then
            log_error "Failed to stop Tomcat process even after force kill"
            exit 1
        else
            log_info "Tomcat process terminated successfully after force kill"
        fi
    else
        log_info "Tomcat process terminated successfully"
    fi
    
    mark_step_completed 10
fi

# Step 11: Modify database connection configuration
log_info "Step 11: Modify database connection configuration"
if is_step_completed 11; then
    log_info "Step 11 already completed, skipping"
else
    DB_CONFIG="$TOMCAT_HOME/webapps/dem/WEB-INF/db.xml"
    if [ -f "$DB_CONFIG" ]; then
        # Backup original file
        cp "$DB_CONFIG" "$DB_CONFIG.bak"
        
        # Create new db.xml configuration
        cat > "$DB_CONFIG" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<ConnectPool>
    <Url>jdbc:dm://127.0.0.1:$PORT_NUM?lobFetchOptimize=true</Url>
    <User>SYSDBA</User>
    <Password>$SYSDBA_PWD</Password>
    <InitPoolSize>5</InitPoolSize>
    <CorePoolSize>10</CorePoolSize>
    <MaxPoolSize>500</MaxPoolSize>
    <KeepAliveTime>60</KeepAliveTime>
    <DbDriver></DbDriver>
    <DbTestStatement>select 1</DbTestStatement>
</ConnectPool>
EOF
        
        log_info "Database connection configuration updated"
    else
        log_error "Database configuration file does not exist: $DB_CONFIG"
        exit 1
    fi
    mark_step_completed 11
fi

# Step 12: Start Tomcat again
log_info "Step 12: Start Tomcat service"
if is_step_completed 12; then
    log_info "Step 12 already completed, skipping"
else
    "$TOMCAT_HOME/bin/startup.sh"
    check_command_result "Failed to start Tomcat"
    log_info "Tomcat started successfully"
    mark_step_completed 12
fi

# Step 13: Start dmagent
log_info "Step 13: Configure and start dmagent"
if is_step_completed 13; then
    log_info "Step 13 already completed, skipping"
else
    # Check if dmagent directory exists
    if [ ! -d "$DMAGENT_HOME" ]; then
        # Check if dmagent zip package exists in current directory
        DMAGENT_ZIP=$(find "$BASE_PATH" -maxdepth 1 -name "dmagent-*.zip" | head -n 1)
        if [ -n "$DMAGENT_ZIP" ] && [ -f "$DMAGENT_ZIP" ]; then
            log_info "dmagent directory does not exist, but found dmagent package in base directory, creating directory..."
            mkdir -p "$DMAGENT_HOME"
            # Move the zip file to dmagent directory
            cp "$DMAGENT_ZIP" "$DMAGENT_HOME/"
            log_info "dmagent directory created and package moved: $DMAGENT_HOME"
        else
            log_error "dmagent directory does not exist: $DMAGENT_HOME"
            log_error "Please create the dmagent directory and place dmagent-*.zip file in it"
            exit 1
        fi
    fi
    
    cd "$DMAGENT_HOME"
    
    # Check if dmagent is already extracted, if not extract it
    if [ ! -f "start.sh" ]; then
        log_info "dmagent not extracted, searching for dmagent package..."
        DMAGENT_ZIP=$(find "$DMAGENT_HOME" -maxdepth 1 -name "dmagent-*.zip" | head -n 1)
        if [ -n "$DMAGENT_ZIP" ] && [ -f "$DMAGENT_ZIP" ]; then
            log_info "Found dmagent package: $DMAGENT_ZIP, extracting..."
            unzip -o "$DMAGENT_ZIP" -d "$DMAGENT_HOME/"
            check_command_result "Failed to extract dmagent package"
            log_info "dmagent package extracted successfully"
        else
            log_error "No dmagent package found in $DMAGENT_HOME. Please ensure a dmagent-*.zip file exists."
            exit 1
        fi
    else
        log_info "dmagent already extracted, skipping extraction"
    fi

    # Set execute permissions for start.sh
    if [ -f "start.sh" ]; then
        chmod +x "start.sh"
        log_info "start.sh execute permission set"
    else
        log_error "start.sh does not exist: $DMAGENT_HOME/start.sh"
        exit 1
    fi

    # Modify agent.ini configuration
    AGENT_INI="$DMAGENT_HOME/agent.ini"
    if [ -f "$AGENT_INI" ]; then
        # Backup original file
        cp "$AGENT_INI" "$AGENT_INI.bak"
        
        # Modify center_url
        sed -i "s|center_url.*=.*|center_url = $DEM_URL|" "$AGENT_INI"
        
        # Modify ap_port (apport)
        sed -i "s|ap_port.*=.*|ap_port = $AGENT_APPPORT|" "$AGENT_INI"
        
        # Modify service_port
        sed -i "s|service_port.*=.*|service_port = $AGENT_SERVICEPORT|" "$AGENT_INI"
        
        log_info "agent.ini configuration updated with ports: ap_port=$AGENT_APPPORT, service_port=$AGENT_SERVICEPORT"
    else
        log_error "agent.ini file does not exist: $AGENT_INI"
        exit 1
    fi

    # Register INSTALL_SERVICE_KEY
    log_info "Register installation service key"
    ./start.sh "INSTALL_SERVICE_KEY" "$INSTALL_SERVICE_KEY"
    check_command_result "Failed to register installation service key"

    # Start dmagent
    log_info "Start dmagent service"
    ./start.sh -d agent.ini
    if [ $? -eq 0 ]; then
        log_info "dmagent started successfully"
    else
        log_error "Failed to start dmagent"
        exit 1
    fi
    mark_step_completed 13
fi

# Installation completed
log_info "DEM automated installation completed!"
log_info "Access URL: $DEM_URL"
log_info "Database port: $PORT_NUM"
log_info "Tomcat port: $TOMCAT_PORT"

# Display service status
log_info "Checking service status:"
echo "1. Database service status:"
"$DB_HOME/DmServicedem" status

echo "2. Tomcat service status:"
ps aux | grep tomcat | grep -v grep

echo "3. dmagent service status:"
ps aux | grep dmagent | grep -v grep
